package cn.edu.hcnu.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.provisioning.InMemoryUserDetailsManager;
import org.springframework.security.web.SecurityFilterChain;

/**
 * @description:
 * @author: Administrator
 * @time: 2023/6/19 17:51
 */
@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true) //注解允许我们在控制器的方法中使用 @PreAuthorize 实现权限分割。
public class SecurityConfig {
    // 1.配置全局的密码编码器
    @Bean
    public PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }

    // 2.配置全局的 UserDetailsService，全局只能有一个，否则构建失败
    @Bean
    public UserDetailsService userDetailsService() {
        BCryptPasswordEncoder encoder = new BCryptPasswordEncoder();
        UserDetails zs = User.builder()
                .username("zs")
                .password(encoder.encode("123"))
                .roles("common")
                .build();
        UserDetails ls = User.builder()
                .username("ls")
                .password(encoder.encode("123"))
                .roles("vip")
                .build();
        return new InMemoryUserDetailsManager(zs, ls);
    }

    @Bean
    public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
        http.authorizeRequests()
                // 对首页统一放行
                .antMatchers("/").permitAll()
                // 对 static/login 文件夹下的静态资源统一放行
                .antMatchers("/login/**").permitAll()
                .antMatchers("/detail/common/**").hasAnyRole("common", "vip")
                .antMatchers("/detail/vip/**").hasRole("vip")
                .anyRequest().authenticated();
        http.formLogin()
                // 对登录页面统一放行
                .loginPage("/userLogin")
                .permitAll()
                .usernameParameter("name").passwordParameter("pwd")
                // 直接登录后默认跳转地址
                .defaultSuccessUrl("/")
                .failureUrl("/userLogin?error");
        http.logout()
                .logoutUrl("/mylogout")
                .logoutSuccessUrl("/");
        http.rememberMe()
                .rememberMeParameter("rememberme")
                // 设置时间，默认值为 14 天
                .tokenValiditySeconds(120);

        http.csrf().disable();
        return http.build();
    }
}
